/*
 * @Description  : 
 * @Author       : zhao
 * @Date         : 2022-06-28 11:16:19
 * @LastEditors  : zhao
 * @LastEditTime : 2022-08-09 09:44:52
 */
/*
 * @Description:
 * @Version: 2.0
 * @Author: zhao
 * @Date: 2022-06-13 14:37:16
 * @LastEditors: zhao
 * @LastEditTime: 2022-07-08 10:25:03
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// 进度条
NProgress.configure({ showSpinner: false }) // NProgress Configuration
//免登录 白名单
const whiteList = [
  "/AboutUs",
  '/InfoPublic/details',
  '/InfoPublic',
  '/login',
  "/home",
  "/AttributeQuery",
  "/SpatialRetrieval",
  "/FileInfoDetails",
  "/Register",
  "/setPassword",
  "/Process",
] // no redirect whiteList

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          const { data } = await store.dispatch('user/getInfo')
          // store.state.user.userInfo = data
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // 没有访问权限的其他页面将重定向到登录页面。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
      // next()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
